package xmlws.actions;

import org.restlet.data.Form;
import org.restlet.data.Status;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.ClientResource;
import org.w3c.dom.Element;
import xmlws.helpers.WebService;
/**
 *
 * @author marya
 */
public class IndexAction extends AbstractAction{

    public void execute() throws Exception {

        String page = "/scripts/login.jsp";
        System.out.println(page);

        if (!isUserAuthenticated()) {
            System.out.println(request.getParameter("login"));
            System.out.println(request.getParameter("password"));
            String login = request.getParameter("login");
            String password = request.getParameter("password");
            if (login == null || login.trim().isEmpty()) {
                throw new Exception("Veuillez renseigner votre login");
            } else if (password == null || password.trim().isEmpty()) {
                throw new Exception("Veuillez renseigner votre mot de passe");
            } else {
                ClientResource client = new ClientResource(WebService.federateur + "/user");
                Form form = new Form();
                form.add("login", login);
                form.add("password", password);
                
                Representation result = client.post(form.getWebRepresentation());
                System.out.println(result);
                System.out.println(client.getResponse().getStatus());
                if (client.getResponse().getStatus().equals(Status.CLIENT_ERROR_NOT_FOUND)) {
                    System.out.println("ERREUR NOT FOUND");
                }else if (client.getResponse().getStatus().equals(Status.CLIENT_ERROR_BAD_REQUEST)) {
                    System.out.println("ERREUR BAD REQUEST");
                } else {
                    DomRepresentation dom = new DomRepresentation(result);
                    Element user = dom.getDocument().getDocumentElement();
                    System.out.println(user.getTextContent());
                    int id = Integer.parseInt(user.getAttribute("id"));
                    String nom = user.getFirstChild().getTextContent();
                    String prenom = user.getFirstChild().getNextSibling().getTextContent();

                    request.getSession().setAttribute("user", prenom + " " + nom);
                    request.getSession().setAttribute("idUser", id);
                }
            }
        } else {
            page = "/user/index.jsp";
        }
        setView(page);


    }
}
